<template>
  <div class="favorite-container">
    <el-card class="favorite-card" v-loading="loading">
      <div slot="header" class="favorite-header">
        <span class="header-title">我的收藏</span>
        <el-button 
          type="text" 
          class="refresh-btn" 
          @click="fetchFavorites"
          :loading="loading"
        >
          <i class="el-icon-refresh"></i> 刷新
        </el-button>
      </div>
      <div v-if="favorites.length === 0" class="empty-favorite">
        <img src="@/assets/Star.png" class="empty-icon" />
        <div>你还没有收藏任何商品~</div>
        <el-button 
          type="primary" 
          class="browse-btn" 
          @click="$router.push('/')"
        >
          去浏览商品
        </el-button>
      </div>
      <el-row v-else gutter="20" class="favorite-list">
        <el-col :xs="24" :sm="12" :md="8" v-for="item in favorites" :key="item.productId">
          <el-card 
            class="favorite-item" 
            :body-style="{ padding: '0px' }"
            shadow="hover"
          >
            <div class="item-content" @click="goToDetail(item.productId)">
              <img 
                :src="getProductImage(item)" 
                class="item-img" 
                :alt="item.title"
              />
              <div class="item-info">
                <div class="item-title">{{ item.title }}</div>
                <div class="item-price">¥ {{ item.price }}</div>
                <div class="item-status" :class="getStatusClass(item.status)">
                  {{ item.status }}
                </div>
                <div class="item-desc">{{ item.description }}</div>
              </div>
            </div>
            <div class="item-actions">
              <el-button 
                type="danger" 
                size="small" 
                icon="el-icon-delete"
                @click.stop="handleUnfavorite(item)"
              >
                取消收藏
              </el-button>
              <el-button 
                type="primary" 
                size="small" 
                icon="el-icon-shopping-cart-2"
                @click.stop="handleOrder(item)"
                :disabled="item.status !== '在售'"
              >
                立即购买
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import InteractionService from '@/Services/InteractionService'
import ProductService from '@/Services/ProductService'

export default {
  name: 'FavoriteView',
  data() {
    return {
      favorites: [],
      loading: false,
      userId: null
    }
  },
  created() {
    // 检查用户是否登录
    if (!localStorage.getItem('isLogged')) {
      this.$router.push('/login')
      return
    }
    // 获取用户ID
    const token = localStorage.getItem('token')
    if (token) {
      try {
        const payload = JSON.parse(atob(token.split('.')[1]))
        this.userId = payload.userId || payload.id || payload.nameid || payload.sub || payload["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"]
      } catch (e) {
        console.error('解析token失败:', e)
        this.$message.error('获取用户信息失败，请重新登录')
        this.$router.push('/login')
        return
      }
    }
    this.fetchFavorites()
  },
  methods: {
    async fetchFavorites() {
      if (!this.userId) return
      
      this.loading = true
      try {
        // 获取用户的收藏记录
        const res = await InteractionService.GetUserInteractions(this.userId)
        if (res && res.code === 200 && res.data) {
          const interactions = Array.isArray(res.data.$values) ? res.data.$values : res.data
          // 过滤出收藏类型的记录（type=1）
          const favoriteInteractions = interactions.filter(i => i.type === 1)
          
          // 获取收藏商品的详细信息
          const productPromises = favoriteInteractions.map(async interaction => {
            try {
              const productRes = await ProductService.GetById(interaction.productId)
              if (productRes && productRes.code === 200 && productRes.data) {
                return {
                  ...productRes.data,
                  interactionId: interaction.interactionId // 保存收藏记录ID，用于取消收藏
                }
              }
              return null
            } catch (error) {
              console.error('获取商品详情失败:', error)
              return null
            }
          })

          const products = await Promise.all(productPromises)
          this.favorites = products.filter(Boolean)
        }
      } catch (error) {
        console.error('获取收藏列表失败:', error)
        this.$message.error('获取收藏列表失败')
      } finally {
        this.loading = false
      }
    },
    getProductImage(product) {
      if (product?.imageBase64) {
        return `data:image/jpeg;base64,${product.imageBase64}`
      }
      return 'https://picsum.photos/320/240'
    },
    getStatusClass(status) {
      switch (status) {
        case '在售':
          return 'status-onsale'
        case '已售出':
          return 'status-sold'
        case '已下架':
          return 'status-offline'
        default:
          return ''
      }
    },
    goToDetail(productId) {
      this.$router.push(`/product/${productId}`)
    },
    async handleUnfavorite(item) {
      try {
        const res = await InteractionService.Delete(item.interactionId)
        if (res && res.code === 200) {
          this.$message.success('取消收藏成功')
          // 从列表中移除该商品
          this.favorites = this.favorites.filter(f => f.productId !== item.productId)
        } else {
          this.$message.error(res?.message || '取消收藏失败')
        }
      } catch (error) {
        console.error('取消收藏失败:', error)
        this.$message.error('取消收藏失败')
      }
    },
    handleOrder(item) {
      if (item.status !== '在售') {
        this.$message.warning('该商品已售出或下架')
        return
      }
      this.$router.push({
        name: 'Order',
        query: {
          productId: item.productId
        }
      })
    }
  }
}
</script>

<style scoped>
.favorite-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 30px 10px;
}
.favorite-card {
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.08);
}
.favorite-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}
.header-title {
  margin-left: 4px;
}
.empty-favorite {
  text-align: center;
  color: #aaa;
  padding: 60px 0 40px 0;
  font-size: 16px;
}
.empty-icon {
  width: 60px;
  height: 60px;
  margin-bottom: 16px;
  opacity: 0.5;
}
.favorite-list {
  margin-top: 20px;
}
.favorite-item {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}
.favorite-item:hover {
  box-shadow: 0 4px 16px 0 rgba(255,215,0,0.15);
}
.item-content {
  cursor: pointer;
  padding: 12px;
}
.item-img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px 8px 0 0;
  background: #f8f8f8;
}
.item-info {
  padding: 12px;
}
.item-title {
  font-size: 16px;
  font-weight: 500;
  color: #222;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
.item-price {
  font-size: 18px;
  color: #ff6a00;
  font-weight: bold;
  margin-bottom: 8px;
}
.item-status {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: white;
  margin-bottom: 8px;
}
.status-onsale {
  background-color: #67C23A;
}
.status-sold {
  background-color: #F56C6C;
}
.status-offline {
  background-color: #909399;
}
.item-desc {
  font-size: 14px;
  color: #888;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  margin-bottom: 12px;
}
.item-actions {
  display: flex;
  justify-content: space-between;
  padding: 12px;
  border-top: 1px solid #eee;
}
.item-actions .el-button {
  flex: 1;
  margin: 0 4px;
}
.refresh-btn {
  font-size: 14px;
  color: #666;
}
.refresh-btn:hover {
  color: #409EFF;
}
.browse-btn {
  margin-top: 16px;
}
@media screen and (max-width: 768px) {
  .favorite-container {
    padding: 15px 10px;
  }
  
  .item-img {
    height: 160px;
  }
  
  .item-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .item-actions .el-button {
    margin: 0;
  }
}
</style> 